package com.power.gatewayservice.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.power.constant.AuthConstants;
import com.power.constant.BusinessEnum;
import com.power.constant.HttpConstans;
import com.power.model.Result;
import com.power.gatewayservice.config.whiteUrlsConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

/**
 * 全局token过滤器
 * 前端约定好令牌存放的位置，统一从请求头中获取Authorization bearer token
 */
@Component
@Slf4j
//Ordered接口是Spring提供的接口，用于定义排序规则。实现该接口的类可以通过实现getOrder()方法来指定排序的优先级
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private whiteUrlsConfig whiteUrlsConfig;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 校验token
     * 1.获取请求路径
     * 2.判断是否可以放行
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象和请求路径
        ServerHttpRequest request = exchange.getRequest();
        RequestPath path = request.getPath();
        //判断这个path是否在配置的白名单集合中
        System.out.println("path:"+path);
        System.out.println("whiteUrlsConfig.getAllowUrls():"+whiteUrlsConfig.getAllowUrls());
        if (whiteUrlsConfig.getAllowUrls().contains(path.toString().trim()))
        {

            //如果path包含在白名单中，直接放行（这里会使路由到Security的配置里面：auth-servicer-->>  com.power.authservice.config.AuthSecurityConfig）
            return chain.filter(exchange);
        }
        //不在白名单中进行认证
        //从请求头中获取token
        String authorization = request.getHeaders().getFirst(AuthConstants.AUTHORIZATION);
        if (StringUtils.hasText(authorization))
        {
         String tokenValue =  authorization.replace(AuthConstants.BEARER,"");
         //判断token是否为空并且redis里是否存在这个token
            if (StringUtils.hasText(tokenValue)&&stringRedisTemplate.hasKey(AuthConstants.Login_Token_prefix+tokenValue))
            {
                //认证通过
                return    chain.filter(exchange);

            }
        }
        //请求信息不通过
        log.info("请求信息不通过",new Date(),path);
        //TODO 认证不通过处理
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().set(HttpConstans.CONTENT_TYPE, HttpConstans.APPLICATION_JSON);
        Result<Object> result = Result.fail(BusinessEnum.UN_AUTHORIZATION);
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes;
        try {
           bytes = objectMapper.writeValueAsBytes(result);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        DataBuffer wrap = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
